package com.linewell.mongodemo.config;

import com.mongodb.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Title: mongodemo
 * @description:
 * @author: hyuhuang@linewell.com
 * @since:2018/12/9
 */
@Configuration
public class MongoConfig {

    @Autowired
    DataBaseConfig dataBaseConfig;

    @Bean(name = "mongoDbFactory")
    public MongoDbFactory mongoDbFactory() {
        //客户端配置（连接数，副本集群验证）
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.requiredReplicaSetName("rs0");
        builder.maxWaitTime(dataBaseConfig.maxWaitTime);
        builder.writeConcern(WriteConcern.valueOf(dataBaseConfig.writeConcern));
        builder.connectTimeout(dataBaseConfig.connectTimeout);
        builder.socketTimeout(dataBaseConfig.socketTimeout);
        builder.socketKeepAlive(dataBaseConfig.socketKeepAlive);
        MongoClientOptions mongoClientOptions = builder.build();
        // MongoDB地址列表
        List<ServerAddress> serverAddresses = new ArrayList<>();
        for (String address : dataBaseConfig.host.split(",")) {
            String[] hostAndPort = address.split(":");
            String host = hostAndPort[0];
            Integer port = Integer.valueOf(hostAndPort[1]);
            ServerAddress serverAddress = new ServerAddress(host, port);
            serverAddresses.add(serverAddress);
        }

        // 连接认证
        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(dataBaseConfig.username,
                dataBaseConfig.database,
                dataBaseConfig.password.toCharArray());
        //创建客户端和Factory
        MongoClient mongoClient = new MongoClient(serverAddresses, Collections.singletonList(mongoCredential), mongoClientOptions);
        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, dataBaseConfig.database);
        return mongoDbFactory;
    }

}
